package person.learn.conf.shiro;

import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import person.learn.entity.realm.TokenRealm;

import javax.servlet.Filter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by barton on 16-2-3.
 */
@Configuration
public class ShiroConfig {

    @Bean(name = "shiroFilter")
    public ShiroFilterFactoryBean shiroFilter() {
        ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
        shiroFilter.setLoginUrl("/");
        shiroFilter.setSuccessUrl("/home");
        shiroFilter.setUnauthorizedUrl("/forbidden");

        Map<String, Filter> filters = new HashMap<>();
        // filters.put("hmacAuthc", new MyHmacAuthcFilter());
        // filters.put("rest", new NoSessionCreationFilter());
        shiroFilter.setFilters(filters);

        Map<String, String> filterChainMap = new HashMap<>();
//        filterChainMap.put("/token", "anon");
//        filterChainMap.put("/user/**", "token");
        shiroFilter.setFilterChainDefinitionMap(filterChainMap);
        shiroFilter.setSecurityManager(securityManager());
        return shiroFilter;
    }

    @Bean(name = "securityManager")
    public org.apache.shiro.mgt.SecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        Collection<Realm> realms = new ArrayList<>();
        realms.add(tokenRealm());
        securityManager.setRealms(realms);
        return securityManager;
    }

    @Bean
    @DependsOn({"lifecycleBeanPostProcessor"})
    public TokenRealm tokenRealm() {
        return new TokenRealm();
    }

    @Bean
    public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
        return new LifecycleBeanPostProcessor();
    }
}
